package com.zjm.find.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjm.find.pojo.News;
import com.zjm.find.pojo.UserManage;
import com.zjm.find.service.ManageService;
import com.zjm.find.utils.JSONResult;
import com.zjm.find.utils.TimeUtils;
import com.zjm.find.utils.UploadFile;
import com.zjm.find.utils.Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Api("后台管理")
@RequestMapping("/manage")
@RestController
public class ManageController {

    @Autowired
    private ManageService manageService;

    @ApiOperation(value = "查看资讯", notes = "查看资讯")
    @GetMapping("/selectNews")
    public JSONResult login(News news,
                            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                            @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit) throws Exception {
        PageHelper.startPage(page, limit);
        PageInfo pageInfo = new PageInfo<>(manageService.selectNews(news));
        return JSONResult.msgAndData("查询成功", pageInfo);
    }

    @ApiOperation(value = "发布资讯", notes = "发布资讯")
    @PostMapping("/postNews")
    public JSONResult postNews(News news,
                               @RequestParam(value = "file", required = true) MultipartFile multipartFile,
                               HttpServletRequest request) throws Exception {
        Map<String, String> params = UploadFile.upload(request);
        String url = params.get("url");
        int i = manageService.postNews(new News(news.getSuid(), news.getTitle(), news.getText(), url, TimeUtils.getDateTime()));
        if (i == 1) {
            return JSONResult.successMsg("创建资讯成功");
        } else {
            return JSONResult.errorMsg("创建资讯失败");
        }
    }

    @ApiOperation(value = "更新资讯", notes = "更新资讯")
    @PostMapping("/updateNews")
    public JSONResult updateNews(News news) throws Exception {
        news.setUpdateTime(TimeUtils.getDateTime());
        if (manageService.updateNews(news)) {
            return JSONResult.successMsg("更新资讯成功");
        } else {
            return JSONResult.errorMsg("更新资讯失败");
        }
    }
}

